package com.caifu.controller.bill;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.HealthyArchiveSearchBean;
import com.caifu.bean.PageDo;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.controller.AbstractController;
import com.caifu.neums.StayBackReasonEnum;
import com.caifu.pojo.*;
import com.caifu.service.*;
import com.caifu.util.DesUtil;
import com.caifu.util.Util;
import com.caifu.vo.BillListVO;
import com.caifu.vo.ElderlyInfoVO;
import com.caifu.vo.YlUserMedicineVo;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 标题： 账单管理
 * 描述： 手工跑账，列表
 * 创建： szt
 */
@Controller
@RequestMapping("bill")
public class BillController extends AbstractController {

    private static final Logger logger = LoggerFactory.getLogger(BillController.class);
    @Autowired
    private IBillService billService;
    @Autowired
    private ElderlyInfoService elderService;

    /**
     * 根据老人用户编号，日期生成账单
     * 指定日期      192.168.1.180:9999/ATPension/bill/createDayBillSin?day=20201125
     * 指定日期用户  192.168.1.180:9999/ATPension/bill/createDayBillSin?day=20201125&userNo=KIF6W26QF88539QS8TDH
     * 2020/11/25
     * codeBy szt
     */
    @GetMapping("createDayBillSin")
    @ResponseBody
    public void createDayBillSin(String day, String userNo) {
        try {
            if(StringUtils.isNotBlank(userNo)){
                //存在用户编号时，生成该用户的日账单
                Result rst = billService.createDayBill(day, userNo);
                if(rst.getCode()==200){
                    System.out.println("生成日账单完成, userNo="+userNo+",day="+day);
                }else{
                    System.out.println("生成日账单失败, "+rst.getMsg());
                }
            }else{
                //不存在该用户时，生成所有用户的日账单
                final String tmpDay = day;
                List<YlElderlyInfo> elderList = billService.listElder();
                elderList.forEach(obj->{
                    try {
                        Result rst = billService.createDayBill(tmpDay, obj.getUserNo());
                        if(rst.getCode()!=200){
                            System.out.println("生成日账单失败, "+rst.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                System.out.println("生成日账单完成, day="+day);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据老人用户编号，日期段生成账单
     * 指定日期      192.168.1.180:9999/ATPension/bill/createDayBillMul?startDay=20201120&endDay=20201125
     * 指定日期用户  192.168.1.180:9999/ATPension/bill/createDayBillMul?startDay=20201120&endDay=20201125&userNo=KIF6W26QF88539QS8TDH
     * 2020/11/25
     * codeBy szt
     */
    @GetMapping("createDayBillMul")
    @ResponseBody
    public void createDayBillMul(String startDay, String endDay, String userNo) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            //起始日期
            Date start = sdf.parse(startDay);
            //结束日期
            Date end = sdf.parse(endDay);
            Date temp = start;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);
            while(temp.getTime()<end.getTime()){
                temp = calendar.getTime();
                String tmpDay = sdf.format(temp);
                if(StringUtils.isNotBlank(userNo)){
                    //存在用户编号时，生成该用户的日账单
                    Result rst = billService.createDayBill(tmpDay, userNo);
                    if(rst.getCode()!=200){
                        System.out.println("生成日账单失败, "+rst.getMsg());
                    }
                }else{
                    //不存在该用户时，生成所有用户的日账单
                    final String tmpSelectDay = tmpDay;
                    List<YlElderlyInfo> elderList = billService.listElder();
                    elderList.forEach(obj->{
                        try {
                            Result rst = billService.createDayBill(tmpSelectDay, obj.getUserNo());
                            if(rst.getCode()!=200){
                                System.out.println("生成日账单失败, "+rst.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
                calendar.add(Calendar.DAY_OF_MONTH,1);
            }
            System.out.println("生成日账单跑批完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 老人列表
     * 2020/11/25
     * codeBy szt
     */
    @RequestMapping("listPage")
    public String listPage(Model model) {
        try {
            //楼苑列表
            model.addAttribute("buildingList", billService.getBuildingListByPensionNo(getUser().getCurrentPensionNo()));
            //每月未结算情况
            model.addAttribute("monthArr", Util.getMonthArrOfYear(Util.currentDate()));
        } catch (Exception ex) {
            logger.error(ex.toString());
            ex.printStackTrace();
        }
        return "bill/bill_list";
    }

    /**
     * 获取老人列表
     * 2020/11/26
     * codeBy szt
     */
    @GetMapping(value = "getElderlyInfoPageList")
    @ResponseBody
    public Result<Object> getElderlyInfoPageList(BillListVO vo) {
        try {
            //vo.setCurrentPage(page);
            //vo.setPageSize(limit);
            if (Util.isNull(vo.getCurrentPage()) || Util.isNull(vo.getPageSize())) {
                return ResultUtil.getPageDataSuccess(new PageDo<>(null, null, null, null, null));
            }
            if(StringUtils.isNotBlank(getUser().getCurrentPensionNo())){
                vo.setPensionNo(getUser().getCurrentPensionNo());
            }
            vo.setUserState("1");
            return billService.getElderlyInfoPageList(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 查看老人账单信息
     * 2020/11/26
     * codeBy szt
     */
    @RequestMapping(value = "jumpElderlyInfoDetail")
    public String jumpElderlyInfoDetail(Model model,String userNo) {
        try {
            //老人基本信息
            model.addAttribute("elderlyInfoOfBase", billService.getElderlyInfoDetailByUserNo(userNo));
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.toString());
        }
        return "bill/bill_info";
    }

    /**
     * 获取账单年份的月份
     * 192.168.1.180:9999/ATPension/bill/getMonthArrOfBillYear?userNo=22BGLV078N2Q9R001B49&year=2019
     * 2020/11/27
     * codeBy szt
     */
    @RequestMapping(value = "getMonthArrOfBillYear")
    @ResponseBody
    public Result<Object> getMonthArrOfBillYear(String userNo, long year) {
        try {
            return billService.getMonthArrOfBillYear(userNo, year);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 获取用户月结算费初始信息
     * 192.168.1.180:9999/ATPension/bill/getUserMonthSettleInfo?userNo=22BGLV078N2Q9R001B49&month=11&year=2020
     * 2020/11/29
     * codeBy szt
     */
    @RequestMapping(value = "getUserMonthSettleInfo")
    @ResponseBody
    public Result<Object> getUserMonthSettleInfo(String userNo ,int year, int month) {
        try {
            return billService.getUserMonthSettleInfo(userNo, year, month);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 生成月账单
     * 2020/11/30
     * codeBy szt
     */
    @RequestMapping(value = "createMonthBill")
    @ResponseBody
    public Result<Object> createMonthBill(YlMonthBill monthBill) {
        try {
            return billService.createMonthBill(monthBill,getUserNo());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 功能描述: 获取用户可缴费日期
     * 192.168.1.180:9999/ATPension/bill/getUserBillAbleDay?userNo=22BGLV078N2Q9R001B49
     * @Param:  [userNo]
     * @Author: szt
     * @Date:   2020/11/30
     */
    @RequestMapping(value = "getUserBillAbleDay")
    @ResponseBody
    public Result<Object> getUserBillAbleDay(String userNo) {
        try {
            return billService.getUserBillAbleDay(userNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 功能描述: 生成缴费记录
     * @Param:  [record]
     * @Author: szt
     * @Date:   2020/11/30
     */
    @RequestMapping(value = "createPaymentRecord")
    @ResponseBody
    public synchronized Result<Object> createPaymentRecord(YlPaymentRecord record) {
        try {
            return billService.createPaymentRecord(record, getUserNo());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /**
     * 获取账单列表
     * 192.168.1.180:9999/ATPension/bill/getBillList?startDay=20201101&endDay=20201201&page=1&limit=5
     * 2020年12月1日
     * codeBy szt
     */
    @RequestMapping("/getBillList")
    @ResponseBody
    public JSONObject getRoleList(String startDay, String endDay, String userNo, int page, int limit){
        JSONObject json = new JSONObject();
        try{
            IPage<Map<String,Object>> billPage = billService.pageBillMaps(startDay, endDay, userNo, page, limit);
            json.put("code","0");
            json.put("msg","成功");
            json.put("count",billPage.getTotal());
            json.put("data",billPage.getRecords());
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取账单列表失败！");
            json.put("code","1");
            json.put("msg","失败");
            return json;
        }
    }

    /**
     * 功能描述: 测试
     * 192.168.1.180:9999/ATPension/bill/test?userNo=22BGLV078N2Q9R001B49
     * @Param:  [userNo]
     * @Author: szt
     * @Date:   2020/11/30
     */
    @RequestMapping(value = "test")
    @ResponseBody
    public synchronized Result<Object> test(String userNo) {
        try {
            return billService.test(userNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }


}
